# coding=utf-8
from django.db import transaction
from django.views.decorators import csrf
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect
from django.shortcuts import RequestContext
from django.shortcuts import render_to_response
from authentication import models as auth_models
from blog import models
from blog import forms

def index(request, *args, **kwargs):
    uid = request.session.get('uid', None)
    try:
        user = auth_models.User.objects.get(id=uid)
    except:
        user = auth_models.User.objects.none()
    return render_to_response('blog/index.html', {
        'user': user,
        'posts': None, # 尚未定义Post部分,暂时返回空
        'title': 'Missuor | blog',
    }, context_instance=RequestContext(request))

def login(request, *args, **kwargs):
    next = request.GET.get('next', 'index')
    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        if username and password:
            try:
                user = auth_models.User.objects.get(
                    username=username,
                    password=password
                )
                request.session['uid'] = user.pk
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect(reverse('index'))
            except:
                pass
    return render_to_response('core/login.html', {
        'title': 'Missuor | login',
        'next': next,
    }, context_instance=RequestContext(request))

def logout(request, *args, **kwargs):
    try:
        del request.session['uid']
    except KeyError:
        pass
    return HttpResponse("注销登录成功, <a href='/'>返回首页</a>")

@csrf.csrf_protect
@transaction.atomic
def register(request, *args, **kwargs):
    if request.method == 'POST':
        form = forms.UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            return render_to_response('core/u.html',
                {'user': user}, context_instance=RequestContext(request))
        else:
            return render_to_response('core/register.html',
                {'form': form}, context_instance=RequestContext(request))
    form = forms.UserForm()
    return render_to_response('core/register.html',
        {'form': form}, context_instance=RequestContext(request))

